package com.wcl.nullmusic.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.ListView;

import com.wcl.nullmusic.R;

/**
 * Created by dllo on 16/1/16.
 */
public class HeaderListView extends ListView implements AbsListView.OnScrollListener {

    private ImageView headerView;

    private int headerView_initHeight;//imageview初始高度

    public void setHeaderView(ImageView headerView) {
        this.headerView = headerView;
    }

    public HeaderListView(Context context) {
        super(context);
        // TODO Auto-generated constructor stub
    }

    public HeaderListView(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        // TODO Auto-generated constructor stub
    }

    public HeaderListView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initFooterView();
 //       this.setOnScrollListener(this);
        // TODO Auto-generated constructor stub
    }

    /**
     * listview焦点改变时--获取iamgeview高度的初始值，该值不能在构造方法中获取
     */
    @Override
    public void onWindowFocusChanged(boolean hasWindowFocus) {
        // TODO Auto-generated method stub
        super.onWindowFocusChanged(hasWindowFocus);
        if (hasWindowFocus) {
            this.headerView_initHeight = headerView.getHeight();
        }
    }

    @SuppressLint("NewApi")
    @Override
    protected boolean overScrollBy(int deltaX, int deltaY, int scrollX,
                                   int scrollY, int scrollRangeX, int scrollRangeY,
                                   int maxOverScrollX, int maxOverScrollY, boolean isTouchEvent) {
        // 滑动过头的时候调用
        boolean bl = resizeHeaderView(deltaY);

        return super.overScrollBy(deltaX, deltaY, scrollX, scrollY, scrollRangeX,
                scrollRangeY, maxOverScrollX, maxOverScrollY, isTouchEvent);
    }

    /**
     * 控制imageview高度的增加
     *
     * @param deltaY 偏移量
     */
    private boolean resizeHeaderView(int deltaY) {
        if (Math.abs((double) deltaY) < 200) {
            if (deltaY < 0) {
                headerView.getLayoutParams().height = headerView.getHeight() - deltaY;
                //重新绘制
                headerView.requestLayout();
            } else {
                headerView.getLayoutParams().height = headerView.getHeight() - deltaY;
                headerView.requestLayout();
            }
        }

        return false;
    }

    @Override
    protected void onScrollChanged(int l, int t, int oldl, int oldt) {
        // TODO Auto-generated method stub
        super.onScrollChanged(l, t, oldl, oldt);
        //获取imageview父控件
        View parent = (View) headerView.getParent();
        //当父控件的top值小于零或者高度大于原始高度时触发
        if (parent.getTop() < 0 || headerView.getHeight() > headerView_initHeight) {
//            headerView.getLayoutParams().height=headerView.getHeight()+parent.getTop();
//            parent.layout(parent.getLeft(),0, parent.getRight(), parent.getHeight());
//            headerView.requestLayout();
        }
    }

    @Override
    public boolean onTouchEvent(MotionEvent ev) {
        // TODO Auto-generated method stub
        if (ev.getAction() == MotionEvent.ACTION_UP || ev.getAction() == MotionEvent.ACTION_CANCEL) {
            MyAnimation animation = new MyAnimation(headerView, headerView_initHeight);
            animation.setDuration(200);
            headerView.startAnimation(animation);
        }
        return super.onTouchEvent(ev);
    }

    private boolean isScrollToBottom; // 是否滑动到底部
    private boolean isLoadingMore = false; // 是否正在加载更多中
    private View footerView; // 脚布局的对象
    private int footerViewHeight; // 脚布局的高度
    private OnRefreshListener mOnRefershListener;

    /**
     * 初始化脚布局
     */
    private void initFooterView() {
        footerView = View.inflate(getContext(), R.layout.listview_load_footer, null);
        footerView.measure(0, 0);
        footerViewHeight = footerView.getMeasuredHeight();
        footerView.setPadding(0, -footerViewHeight, 0, 0);
        this.addFooterView(footerView);
    }

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_IDLE
                || scrollState == SCROLL_STATE_FLING) {
            // 判断当前是否已经到了底部
            if (isScrollToBottom && !isLoadingMore) {
                isLoadingMore = true;
                // 当前到底部
                //  Log.i(TAG, "加载更多数据");
                footerView.setPadding(0, 0, 0, 0);
                this.setSelection(this.getCount());

                if (mOnRefershListener != null) {
                    mOnRefershListener.onLoadingMore();
                }
            }
        }
    }

    private int firstVisibleItemPosition; // 屏幕显示在第一个的item的索引

    /**
     * 当滚动时调用
     *
     * @param firstVisibleItem 当前屏幕显示在顶部的item的position
     * @param visibleItemCount 当前屏幕显示了多少个条目的总数
     * @param totalItemCount   ListView的总条目的总数
     */
    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        firstVisibleItemPosition = firstVisibleItem;

        if (getLastVisiblePosition() == (totalItemCount - 1)) {
            isScrollToBottom = true;
        } else {
            isScrollToBottom = false;
        }
    }

    /**
     * 设置刷新监听事件
     *
     * @param listener
     */
    public void setOnRefreshListener(OnRefreshListener listener) {
        mOnRefershListener = listener;
    }

    /**
     * 隐藏脚布局
     */
    public void hideFooterView() {
        footerView.setPadding(0, -footerViewHeight, 0, 0);
        isLoadingMore = false;
    }

    public class MyAnimation extends Animation {

        private ImageView header_iv;
        private int currentHeight;
        private int targetHeight;
        private int poorHeight;

        public MyAnimation(ImageView iv, int targetHeight) {
            this.header_iv = iv;
            this.targetHeight = targetHeight;
            this.currentHeight = iv.getHeight();
            this.poorHeight = this.currentHeight - this.targetHeight;
        }

        /**
         * 动画执行期间执行该方法，不断执行
         * interpolatedTime：当前时间与duration的时间比（时间执行百分比）
         */
        @Override
        protected void applyTransformation(float interpolatedTime,
                                           Transformation t) {
            // TODO Auto-generated method stub
            super.applyTransformation(interpolatedTime, t);
            this.header_iv.getLayoutParams().height = (int) (currentHeight - poorHeight * interpolatedTime);
            this.header_iv.requestLayout();
        }
    }

    public interface OnRefreshListener {
        /**
         * 上拉加载更多
         */
        void onLoadingMore();
    }

}